package com.youxin.logcenter.common;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.youxin.busfoundation.bean.BusinessMessages;
import com.youxin.busfoundation.bean.ResponseMessage;
import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.logcenter.LogCenterApplication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 全局异常类
 * @author yingde.cao
 *
 */

//@RestControllerAdvice

//@ControllerAdvice
//public class GlobalExceptionHandler {
//	
//    @ExceptionHandler(value = Exception.class)
//    @ResponseBody
//    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, Exception e) throws Exception {
//        ErrorInfo<String> r = new ErrorInfo<>();
//        r.setMessage(e.getMessage());
//        r.setCode(ErrorInfo.ERROR);
//        r.setData("Some Data");
//        r.setUrl(req.getRequestURL().toString());
//        return r;
//    }
//}


@RestController
@RequestMapping("/error")

public class GlobalExceptionHandler extends AbstractErrorController {
	private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(GlobalExceptionHandler.class);

    @Autowired
    public GlobalExceptionHandler(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }
 
    @Override
    public String getErrorPath() {
        return "/error";
    }
 
    @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseObject error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);        
        final Object exception = (Object) request.getAttribute("javax.servlet.error.exception");
        if(exception!=null)
        {
        	if(exception instanceof Throwable)
        	{
        		Throwable throwable=(Throwable)exception;
        		logger.error("application error", throwable);
        		return ResponseObject.systemError(throwable);
        	}
        	logger.error("application error:"+exception.toString());        	
        	return ResponseObject.systemError(exception.toString());
        }
        
        return new ResponseObject(status.value(),status.getReasonPhrase());
    }
}
